import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'package:dailyEn/global.dart';
import 'package:dailyEn/toast.dart';
import 'package:dailyEn/api.dart';
import 'package:intl/intl.dart';
import 'dart:typed_data';
import 'dart:ui';

import 'package:provider/provider.dart';

class DetailPage extends StatefulWidget {
  DetailPage({Key key, this.href, this.date}) : super(key: key);
  final String href;
  final String date;
  @override
  _DetailPageState createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  GlobalKey globalKey = GlobalKey();
  var _data;
  var _showBtn = true;

  AudioPlayer audioPlayer = AudioPlayer();
  // 音频总时间
  Duration duration;
  // 音频当前时间
  Duration position = Duration(milliseconds: 6400);
  // 音频是否正在播放
  bool complete = false;
  bool circlePlay = false;

  // 开始播放
  play() async {
    try {
      final result =
          await audioPlayer.play(_data['result']['audio'], position: position);
      audioPlayer.setPlaybackRate(playbackRate: 1.0);
      if (result == 1) setState(() => {complete = true});
    } catch (e) {
      print(e);
    }
  }

  // 暂停播放
  void pause() async {
    final result = await audioPlayer.pause();
    if (result == 1) {
      setState(() {
        complete = false;
      });
    }
  }

  //停止播放
  void stop() {
    audioPlayer.stop();
  }

  Future<Uint8List> _capturePng() async {
    setState(() => {_showBtn = false});
    try {
      Future.delayed(Duration(milliseconds: 100), () async {
        RenderRepaintBoundary boundary =
            globalKey.currentContext.findRenderObject();
        var image = await boundary.toImage(pixelRatio: 3.0);
        ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
        Uint8List pngBytes = byteData.buffer.asUint8List();
        final result = await ImageGallerySaver.saveImage(pngBytes,
            quality: 100, name: "Daily口语");
        Toast.show(context,
            msg: '打卡图片保存${result['isSuccess'] ? "成功" : "失败"}', duration: 1);
        setState(() {
          _showBtn = true;
        });
      });
    } catch (e) {
      print(e);
      setState(() {
        _showBtn = true;
      });
    }
    return null;
  }

  @override
  void initState() {
    getData(DateTime.parse(widget.date));
    audioPlayer.onPlayerStateChanged.listen((state) {
      // 播放完毕
      if (state == AudioPlayerState.COMPLETED) {
        // 重置时长及播放状态
        setState(() {
          position = Duration(milliseconds: 6400);
          duration = Duration(milliseconds: 0);
          complete = false;
        });
        // if (circlePlay) play();
      }
    });

    // 播放进度监听
    audioPlayer.onAudioPositionChanged.listen((Duration p) {
      setState(() {
        position = p;
      });
    });
    super.initState();
  }

  @override
  void dispose() {
    stop();
    super.dispose();
  }

  getData(date) async {
    var str = ['一', '二', '三', '四', '五', '六', '日'];
    var strEn = [
      'Monday',
      'Tuesday',
      'Wednesday',
      'Thursday',
      'Friday',
      'Saturday',
      'Sunday'
    ];
    var _date = DateFormat('yyyy年MM月dd日').format(date);
    var _day = date.day;
    var _weekday = str[date.weekday - 1];
    var _weekdayEn = strEn[date.weekday - 1];
    var res = await detail(widget.href);
    setState(() {
      _data = {
        'result': res,
        'day': _day,
        'date': _date,
        'weekday': _weekday,
        'weekdayEn': _weekdayEn,
      };
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'Daily口语',
          style: TextStyle(
            color: Global.fontColor,
            fontSize: 13,
            fontWeight: FontWeight.bold,
          ),
        ),
        iconTheme: IconThemeData(color: Global.fontColor),
        backgroundColor: Global.backgroundColor,
        brightness: Brightness.light,
        elevation: 0,
      ),
      body: _data == null
          ? Container(
              color: Global.backgroundColor,
              child: Center(
                child: CircularProgressIndicator(
                  backgroundColor: Global.backgroundColor,
                  valueColor: AlwaysStoppedAnimation<Color>(Global.fontColor),
                ),
              ),
            )
          : Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              decoration: BoxDecoration(
                color: Global.backgroundColor,
              ),
              margin: EdgeInsets.fromLTRB(15, 5, 15, 5),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  RepaintBoundary(
                    key: globalKey,
                    child: Container(
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Global.fontColor.withOpacity(.2),
                          width: .5,
                        ),
                        color: Global.backgroundColor,
                      ),
                      margin: EdgeInsets.all(13),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            child: FadeInImage.assetNetwork(
                              placeholder: 'assets/images/place.jpg',
                              fadeInDuration: Duration(milliseconds: 500),
                              image:
                                  'https://api.ixiaowai.cn/gqapi/gqapi.php?t=' +
                                      _data['date'],
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.all(20),
                            child: Column(
                              children: [
                                //                          'day': _day,
                                // 'date': _date,
                                // 'weekday': _weekday,
                                // 'weekdayEn': _weekdayEn,
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Text(
                                      _data['day'].toString(),
                                      style: TextStyle(
                                        color: Global.fontColor,
                                        fontSize: 40,
                                        fontWeight: FontWeight.w600,
                                        fontFamily: 'SarasaMonoSCItalic',
                                      ),
                                    ),
                                    Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      children: [
                                        Row(
                                          children: [
                                            Text(
                                              _data['date'].toString(),
                                              style: TextStyle(
                                                color: Global.fontSecondColor,
                                                fontSize: 13,
                                                fontWeight: FontWeight.w400,
                                                fontFamily:
                                                    'SarasaMonoSCItalic',
                                              ),
                                            ),
                                          ],
                                        ),
                                        SizedBox(height: 5),
                                        Row(
                                          children: [
                                            Text(
                                              '星期' +
                                                  _data['weekday'].toString(),
                                              style: TextStyle(
                                                color: Global.fontSecondColor,
                                                fontSize: 11,
                                                fontWeight: FontWeight.w400,
                                                fontFamily:
                                                    'SarasaMonoSCItalic',
                                              ),
                                            ),
                                            SizedBox(width: 15),
                                            Text(
                                              _data['weekdayEn'].toString(),
                                              style: TextStyle(
                                                color: Global.fontSecondColor,
                                                fontSize: 11,
                                                fontWeight: FontWeight.w400,
                                                fontFamily:
                                                    'SarasaMonoSCItalic',
                                              ),
                                            ),
                                          ],
                                        ),
                                      ],
                                    )
                                  ],
                                ),

                                SizedBox(height: 20),
                                Container(
                                  decoration: BoxDecoration(
                                    border: Border(
                                      bottom: BorderSide(
                                        width: .5,
                                        color: Global.fontSecondColor
                                            .withOpacity(.2),
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(height: 20),
                                Text(
                                  _data['result']['en'],
                                  style: TextStyle(
                                    color: Global.fontColor,
                                    fontSize: 20,
                                    fontWeight: FontWeight.w600,
                                    fontFamily: 'SarasaMonoSCItalic',
                                  ),
                                ),
                                SizedBox(height: 20),
                                Text(
                                  _data['result']['zh'],
                                  style: TextStyle(
                                    color: Global.fontSecondColor,
                                    fontSize: 17,
                                    fontWeight: FontWeight.w600,
                                    fontFamily: 'SarasaMonoSCItalic',
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  _showBtn
                      ? Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            RaisedButton.icon(
                              padding: EdgeInsets.fromLTRB(10, 5, 10, 5),
                              color: Global.backgroundColor,
                              elevation: 0,
                              icon: Icon(
                                complete ? Icons.pause : Icons.play_arrow,
                                color: Global.fontColor.withOpacity(.6),
                                size: 28,
                              ),
                              label: Text(
                                complete ? '暂停朗读' : '口语朗读',
                                style: TextStyle(
                                  color: Global.fontColor.withOpacity(.6),
                                  fontSize: 12,
                                ),
                              ),
                              onPressed: () {
                                complete ? pause() : play();
                              },
                            ),
                            RaisedButton.icon(
                              padding: EdgeInsets.fromLTRB(10, 5, 10, 5),
                              color: Global.backgroundColor,
                              elevation: 0,
                              icon: Icon(
                                Icons.file_download,
                                color: Global.fontColor.withOpacity(.6),
                                size: 24,
                              ),
                              label: Text(
                                '生成打卡图',
                                style: TextStyle(
                                  color: Global.fontColor.withOpacity(.6),
                                  fontSize: 12,
                                ),
                              ),
                              onPressed: () {
                                _capturePng();
                              },
                            ),
                          ],
                        )
                      : Container()
                ],
              ),
            ),
    );
  }
}
